<template>
  <div class="page-container">
    <!--工具栏-->
    <div
      class="toolbar"
      style="float: left; padding-top: 10px; padding-left: 15px"
    >
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item>
          <kt-button
            icon="fa fa-search"
            :label="$t('action.search')"
            perms="sys:dept:view"
            type="primary"
            @click="findTreeData(null)"
          />
        </el-form-item>
        <el-form-item>
          <kt-button
            icon="fa fa-plus"
            :label="$t('action.add')"
            perms="sys:dept:add"
            type="primary"
            @click="handleAdd"
          />
        </el-form-item>
      </el-form>
    </div>
    <!--表格树内容栏-->
    <el-table
      :data="tableTreeDdata"
      :row-class-name="tableRowClassName"
      size="mini"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="$t('action.loading')"
      stripe
      :default-expand-all="true"
    >
      <el-table-column
        header-align="center"
        align="center"
        width="60"
        type="index"
        label="序号"
      >
      </el-table-column>
      <table-tree-column
        prop="name"
        header-align="center"
        treeKey="id"
        width="300"
        label="机构名称"
      >
      </table-tree-column>
      <el-table-column
        prop="parentName"
        header-align="center"
        align="center"
        width="160"
        label="上级机构"
      >
      </el-table-column>
      <el-table-column
        prop="orderNum"
        header-align="center"
        align="center"
        width="80"
        label="顺序"
      >
      </el-table-column>
      <el-table-column
        prop="createBy"
        header-align="center"
        align="center"
        width="100"
        label="创建人"
      >
      </el-table-column>
      <el-table-column
        prop="delFlag"
        header-align="center"
        align="center"
        label="状态"
        :formatter="statusFormat1"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间"
        :formatter="dateFormat1"
      >
      </el-table-column>
      <el-table-column
        prop="lastUpdateTime"
        header-align="center"
        align="center"
        label="更新时间"
        :formatter="dateFormat1"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="180"
        :label="$t('action.operation')"
      >
        <template slot-scope="scope">
          <kt-button
            icon="fa fa-edit"
            :label="$t('action.edit')"
            perms="sys:dept:edit"
            @click="handleEdit(scope.row)"
          />
          <kt-button
            icon="fa fa-trash"
            :label="$t('action.delete')"
            perms="sys:dept:delete"
            type="danger"
            @click="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增修改界面 -->
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      width="40%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="submitForm()"
        label-width="80px"
        :size="size"
        style="text-align: left"
      >
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="机构名称"></el-input>
        </el-form-item>
        <el-form-item label="上级机构" prop="parentName">
          <popup-tree-input
            :data="popupTreeData"
            :props="popupTreeProps"
            :prop="
              dataForm.parentName == null ? '顶级菜单' : dataForm.parentName
            "
            :nodeKey="'' + dataForm.parentId"
            :currentChangeHandle="handleTreeSelectChange"
          >
          </popup-tree-input>
        </el-form-item>
        <el-form-item label="机构状态" prop="delFlag">
          <el-select
            v-model="dataForm.delFlag"
            filterable
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="dataForm.type !== 2"
          label="排序编号"
          prop="orderNum"
        >
          <el-input-number
            v-model="dataForm.orderNum"
            controls-position="right"
            :min="0"
            label="排序编号"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="dialogVisible = false">{{
          $t("action.cancel")
        }}</el-button>
        <el-button :size="size" type="primary" @click="submitForm()">{{
          $t("action.comfirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import TableTreeColumn from "@/views/Core/TableTreeColumn";
import PopupTreeInput from "@/components/PopupTreeInput";
import FaIconTooltip from "@/components/FaIconTooltip";
import { dateFormat } from "@/utils/datetime";
export default {
  components: {
    PopupTreeInput,
    KtButton,
    TableTreeColumn,
    FaIconTooltip,
  },
  data() {
    return {
      size: "small",
      loading: false,
      filters: {
        name: "",
      },
      tableTreeDdata: [],
      dialogVisible: false,
      dataForm: {
        id: 0,
        name: "",
        parentId: 0,
        parentName: "",
        orderNum: 0,
        delFlag: "",
      },
      dataRule: {
        name: [
          { required: true, message: "机构名称不能为空", trigger: "blur" },
        ],
        parentName: [
          { required: true, message: "上级机构不能为空", trigger: "change" },
        ],
        delFlag: [
          { required: true, message: "请选择机构状态", trigger: "change" },
        ],
      },
      popupTreeData: [],
      popupTreeProps: {
        label: "name",
        children: "children",
      },
      options: [
        { value: "0", label: "立即生效" },
        { value: "1", label: "撤销机构" },
      ],
      optionValue: "",
    };
  },
  methods: {
    // 获取数据
    findTreeData: function () {
      this.loading = true;
      this.$api.dept
        .findDeptTree()
        .then((res) => {
          if (res.msg != null) {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          } else {
            this.tableTreeDdata = res.data;
            this.popupTreeData = this.getParentMenuTree(res.data);
            this.loading = false;
          }
        })
        .catch((res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        });
    },
    // 获取上级机构树
    getParentMenuTree: function (tableTreeDdata) {
      let parent = {
        parentId: 0,
        name: "顶级菜单",
        children: tableTreeDdata,
      };
      return [parent];
    },
    // 显示新增界面
    handleAdd: function () {
      this.dialogVisible = true;
      this.dataForm = {
        id: 0,
        name: "",
        parentId: 0,
        parentName: "",
        orderNum: 0,
      };
    },
    // 显示编辑界面
    handleEdit: function (row) {
      this.dialogVisible = true;
      Object.assign(this.dataForm, row);
      this.dataForm.delFlag = "";
    },
    // 删除
    handleDelete(row) {
      this.$confirm("确认彻底删除选中机构吗？", "温馨提示", {
        type: "warning",
      }).then(() => {
        let params = this.getDeleteIds([], row);
        this.$api.dept
          .batchDelete(params)
          .then((res) => {
            if (res.msg != null) {
              this.$message({
                showClose: true,
                message: res.msg,
                type: "error",
              });
            } else {
              this.findTreeData();
              this.$message({ message: "恭喜您，删除成功！", type: "success" });
            }
          })
          .catch((res) => {
            this.$message({
              message: res.message,
              type: "error",
            });
          });
      });
    },
    // 获取删除的包含子机构的id列表
    getDeleteIds(ids, row) {
      ids.push({ id: row.id });
      if (row.children != null) {
        for (let i = 0, len = row.children.length; i < len; i++) {
          this.getDeleteIds(ids, row.children[i]);
        }
      }
      return ids;
    },

    // 机构树选中
    handleTreeSelectChange(data, node) {
      this.dataForm.parentId = data.id;
      this.dataForm.parentName = data.name;
    },
    // 表单提交
    submitForm() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "温馨提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            this.$api.dept.save(params).then((res) => {
              this.editLoading = false;
              if (res.code == 200) {
                this.$message({ message: "操作成功", type: "success" });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
              this.findTreeData();
            });
          });
        }
      });
    },
    // 时间格式化
    dateFormat1: function (row, column, cellValue, index) {
      return dateFormat(row[column.property]);
    },
    // 状态格式化
    statusFormat1: function (row, column, cellValue, index) {
      let status = row[column.property];
      switch (status) {
        case 0:
          return "正常";
          break;
        case 1:
          return "已失效";
          break;
        default:
          return "其它";
          break;
      }
    },
    //顶级机构的行标准显示
    tableRowClassName({ row, rowIndex }) {
      if (row.parentId == null) {
        return "root-row";
      }
      return "";
    },
  },
  mounted() {
    this.findTreeData();
  },
};
</script>

<style>
.el-table .root-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>